<template>
  <div class="interview-questions-container">
    <a-card title="面试押题生成" :bordered="false">
      <a-alert
        message="上传您的简历，系统将根据您的技能和经验生成可能的面试题目"
        description="提前准备面试题目，有助于您在面试中更加从容应对，展现最佳状态"
        type="info"
        show-icon
        style="margin-bottom: 20px"
      />

      <div class="upload-section">
        <a-upload
          v-model:file-list="fileList"
          :before-upload="beforeUpload"
          :remove="handleRemove"
          :max-count="1"
          :multiple="false"
          :accept="'.pdf,.doc,.docx'"
        >
          <a-button type="primary" :disabled="fileList.length >= 1">
            <upload-outlined /> 上传简历
          </a-button>
          <div class="upload-hint">支持 PDF、Word 格式文件</div>
        </a-upload>
      </div>

      <a-divider />

      <div class="action-buttons">
        <a-button
          type="primary"
          :disabled="fileList.length === 0 || loading"
          @click="generateQuestions"
          :loading="loading"
        >
          生成面试题
        </a-button>
        <a-button :disabled="!questions.length" @click="copyResult" style="margin-left: 10px">
          复制到剪贴板
        </a-button>
      </div>

      <a-divider />

      <div class="result-section">
        <a-spin :spinning="loading">
          <div v-if="questions.length > 0" class="result-content">
            <a-typography-title :level="4">可能的面试题目</a-typography-title>
            <a-list :data-source="questions" :item-layout="'vertical'">
              <template #renderItem="{ item, index }">
                <a-list-item>
                  <a-card class="question-card">
                    <div class="question-content">
                      <div class="question-title">{{ index + 1 }}. {{ item }}</div>
                    </div>
                  </a-card>
                </a-list-item>
              </template>
            </a-list>
          </div>
          <a-empty v-else description="暂无内容，请上传简历并点击生成" />
        </a-spin>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
// @ts-ignore: 忽略模块类型声明错误
import { doSpecialExerciseUsingPost } from '@/api/specialExerciseController'

// 文件列表
const fileList = ref<any[]>([])
// 生成的问题
const questions = ref<string[]>([])
// 加载状态
const loading = ref<boolean>(false)

// 文件上传前检查
const beforeUpload = (file: File) => {
  // 检查文件类型
  const isValidFileType =
    file.type === 'application/pdf' ||
    file.type === 'application/msword' ||
    file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

  if (!isValidFileType) {
    message.error('只能上传 PDF 或 Word 文件!')
    return false
  }

  // 检查文件大小
  const isLessThan10M = file.size / 1024 / 1024 < 10
  if (!isLessThan10M) {
    message.error('文件必须小于 10MB!')
    return false
  }

  // 文件验证通过，但返回false阻止自动上传
  return false
}

// 删除文件
const handleRemove = () => {
  fileList.value = []
  questions.value = [] // 清空结果
  return true
}

// 生成面试题
const generateQuestions = async () => {
  if (fileList.value.length === 0) {
    message.warning('请先上传简历')
    return
  }

  loading.value = true
  message.success('请稍后查看面试题目')

  try {
    // 获取上传的文件对象
    const file = fileList.value[0].originFileObj
    // 调用后端接口生成面试题
    const params = { type: 'interview_question' }
    const data = await doSpecialExerciseUsingPost(params, {}, file)

    if (data.code === 0) {
      console.log('接口返回数据:', data.data)

      // 处理返回的数据
      if (Array.isArray(data.data)) {
        // 如果返回的是数组，直接使用
        questions.value = data.data
      } else if (typeof data.data === 'string') {
        try {
          // 尝试解析字符串为JSON数组
          const parsedData = JSON.parse(data.data)
          if (Array.isArray(parsedData)) {
            questions.value = parsedData
          } else {
            // 如果解析的不是数组，则作为单个问题添加
            questions.value = [data.data]
          }
        } catch (e) {
          // 如果解析失败，则将字符串作为单个问题
          questions.value = [data.data]
        }
      } else {
        message.warning('返回数据格式不符合预期')
        questions.value = ['返回数据格式不符合预期']
      }

      message.success('面试题生成成功')
    } else {
      message.error(data.message || '生成失败，请重试')
    }
  } catch (error) {
    console.error('生成失败:', error)
    message.error('生成失败，请重试')
  } finally {
    loading.value = false
  }
}

// 复制到剪贴板
const copyResult = () => {
  if (questions.value.length === 0) {
    message.warning('暂无内容可复制')
    return
  }

  let textToCopy = questions.value.map((q, index) => `${index + 1}. ${q}`).join('\n\n')

  navigator.clipboard
    .writeText(textToCopy)
    .then(() => {
      message.success('已复制到剪贴板')
    })
    .catch((err) => {
      console.error('复制失败:', err)
      message.error('复制失败，请手动复制')
    })
}
</script>

<style scoped>
.interview-questions-container {
  padding: 20px;
}

.upload-section {
  margin: 20px 0;
}

.upload-hint {
  color: #999;
  margin-top: 8px;
  font-size: 12px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.result-section {
  margin-top: 20px;
}

.question-card {
  width: 100%;
  margin-bottom: 10px;
  background-color: #f9f9f9;
}

.question-content {
  padding: 10px;
}

.question-title {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

:deep(.ant-upload-list-item-name) {
  font-weight: bold;
}
</style> 